package com.lebang.service.cences;


import com.lebang.component.UMengCensusComponent;
import com.lebang.domain.CencesCoreData;
import com.lebang.example.CencesCoreDataExample;
import com.lebang.mapper.*;
import com.lebang.model.AotianModelRequest;
import com.lebang.model.ChannelInfoModel;
import com.lebang.model.MyConfig;
import com.lebang.model.cences.CencesCoreDataModel;
import com.lebang.model.cences.DownloadMemberFinishRecordCount;
import com.lebang.model.enums.UmengPeriodTypeEnum;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.statistics.StatisticsRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: hwq
 * @Date: 2019/10/9 9:32
 * @Version 1.0
 */
@Service
@Slf4j
public class CencesCoreDataService {
    @Autowired
    private LbbMemberMapper lbbMemberMapper;
    @Autowired
    private LbbMemberTradeMapper tradeMapper;
    @Autowired
    private MemberNewTradeMapper memberNewTradeMapper;
    @Autowired
    private LbbMemberRecordMapper lbbMemberRecordMapper;
    @Autowired
    private MemberCashWithdrawalMapper memberCashWithdrawalMapper;
    @Autowired
    private DownloadMemberRecordMapper downloadMemberRecordMapper;
    @Autowired
    private CencesCoreDataMapper cencesCoreDataMapper;

    @Autowired
    private UMengCensusComponent uMengCensusComponent;

    /**
     * 开始统计
     *
     * @param end
     */
    public void starDataInit(LocalDateTime end) {
        LocalDateTime star = end.minusDays(1);
//        //昨日开始日期
//        String starr = star.toLocalDate().format(DateTimeFormatter.ISO_DATE).replace("-", "");
//        //昨日结束日期
//        String endd = end.toLocalDate().format(DateTimeFormatter.ISO_DATE).replace("-", "");
        //如果应用为南瓜，一瓜，公交不统计
        if(MyConfig.getEnv()==10||MyConfig.getEnv()==7||MyConfig.getEnv()==8){
                return;
        }
        try {

            List<String> appStores = lbbMemberMapper.selectBrand();

            //不同渠道注册人数
            List<CencesCoreDataModel> registers = lbbMemberMapper.resisterMemberCountGroupByAppStore(star, end);
            Map<String, List<CencesCoreDataModel>> registerMap = registers.stream().collect(Collectors.groupingBy(CencesCoreDataModel::getAppStore));

            //截图任务收入
            List<StatisticsRecord> statisticsRecordList = lbbMemberRecordMapper.sumRecordGroupByAppStore(star, end, MyConfig.getEnv());
            Map<String, List<StatisticsRecord>> commonMap = statisticsRecordList.stream().collect(Collectors.groupingBy(StatisticsRecord::getAppStore));

            //提现
            List<StatisticsRecord> todayAllCashMoneys = tradeMapper.todayAllCashMoneyAppStore(star, end);
            List<StatisticsRecord> newTodayAllCashMoneys = memberCashWithdrawalMapper.todayAllCashMoneyAppStore(star, end);
            Map<String, List<StatisticsRecord>> tradeMap = todayAllCashMoneys.stream().collect(Collectors.groupingBy(StatisticsRecord::getAppStore));
            Map<String, List<StatisticsRecord>> drawlMap = newTodayAllCashMoneys.stream().collect(Collectors.groupingBy(StatisticsRecord::getAppStore));

            //每日必赚
            List<DownloadMemberFinishRecordCount> downloadMemberFinishRecordCounts = downloadMemberRecordMapper.countByCategory(star, end);
            downloadMemberFinishRecordCounts.forEach(s -> {
                s.setAppStoreIsNewMember(s.getAppStore() + ":"+s.getIsNewMember());
            });
            Map<String, List<DownloadMemberFinishRecordCount>> downLoadMap = downloadMemberFinishRecordCounts.stream().collect(Collectors.groupingBy(DownloadMemberFinishRecordCount::getAppStoreIsNewMember));


            //获取不同渠道收支
            List<CencesCoreDataModel> coreData = memberNewTradeMapper.selectByAppStore(star, end,null);
            //转map
            coreData.forEach(s -> {
                s.setCategoryAppStore(s.getCategory() + ":" + s.getAppStore());
            });
            Map<String, List<CencesCoreDataModel>> collect = coreData.stream().collect(Collectors.groupingBy(CencesCoreDataModel::getCategoryAppStore));

            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
            int time = Integer.parseInt(end.toLocalDate().minusDays(1).format(df));

            DateTimeFormatter dff = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String queryTime = end.toLocalDate().minusDays(1).format(dff);

            //全部渠道
            CencesCoreData all = new CencesCoreData(time, "all");

            List<ChannelInfoModel>  allAppStoreData =  uMengCensusComponent.queryAllAppStore(queryTime,1,300);
            Map<String, List<ChannelInfoModel>> channelMap = allAppStoreData.stream().collect(Collectors.groupingBy(ChannelInfoModel::getChannel));

            appStores.forEach(s -> {
                //遍历渠道
                CencesCoreData cencesCoreData = new CencesCoreData(time, s);
                //新增用户(友盟)
                cencesCoreData.setIncreaseMember(increaseMemberNum(channelMap,s));
                //注册人数
                cencesCoreData.setRegisterMember(countRegisterNum(registerMap, s));
                //活跃用户(友盟)
                cencesCoreData.setActiveMember(activeMemberNum(channelMap,s));
                //注册率 注册/新增*100%
                if(cencesCoreData.getIncreaseMember()==0){
                    cencesCoreData.setRegisterRate(BigDecimal.ZERO);
                }else{
                    cencesCoreData.setRegisterRate(new BigDecimal(cencesCoreData.getRegisterMember()).divide(new BigDecimal(cencesCoreData.getIncreaseMember()),2,RoundingMode.HALF_UP));
                }
                //sdk营收
                cencesCoreData.setSdkProfit(appStoreSdkProfit(s, collect).setScale(2, RoundingMode.HALF_UP));
                //截图营收
                cencesCoreData.setCommonProfit(appStoreCommonProfit(s, commonMap).setScale(2, RoundingMode.HALF_UP));
                //提现支出
                cencesCoreData.setCashOutput(appStoreCash(s, tradeMap, drawlMap).setScale(2, RoundingMode.HALF_UP));
                //有效用户数
                cencesCoreData.setEffectMember(getMemberNum(s, downLoadMap));
                //完成任务数
                cencesCoreData.setFinishTaskNun(getTaskFinish(s, downLoadMap));
                //有效转化率 有效用户数/新增用户*100%
                if(cencesCoreData.getIncreaseMember()==0){
                    cencesCoreData.setEffectMemberRate(BigDecimal.ZERO);
                }else{
                    cencesCoreData.setEffectMemberRate(new BigDecimal(cencesCoreData.getEffectMember()).divide(new BigDecimal(cencesCoreData.getIncreaseMember()),2,RoundingMode.HALF_UP));
                }
                cencesCoreDataMapper.insertToCommon(cencesCoreData);
                sumData(cencesCoreData, all);

            });

            //注册率 注册/新增*100%
            if(all.getIncreaseMember()==0){
                all.setRegisterRate(BigDecimal.ZERO);
            }else{
                all.setRegisterRate(new BigDecimal(all.getRegisterMember()).divide(new BigDecimal(all.getIncreaseMember()),2,RoundingMode.HALF_UP));
            }
            //有效转化率 有效用户数/新增用户*100%
            if(all.getIncreaseMember()==0){
                all.setEffectMemberRate(BigDecimal.ZERO);
            }else{
                all.setEffectMemberRate(new BigDecimal(all.getEffectMember()).divide(new BigDecimal(all.getIncreaseMember()),2,RoundingMode.HALF_UP));
            }

            all.setIncreaseMember(uMengCensusComponent.queryIncreaseMember(queryTime,queryTime,UmengPeriodTypeEnum.daily.name()));
            all.setActiveMember(uMengCensusComponent.queryActiveMember(queryTime,queryTime,UmengPeriodTypeEnum.daily.name()));

            cencesCoreDataMapper.insertToCommon(all);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 所有渠道活跃
     * @param allAppStoreData
     * @return
     */
    private Integer allActiveMember(List<ChannelInfoModel> allAppStoreData) {

        Integer num=0;
        for(ChannelInfoModel channelInfoModel:allAppStoreData){
            num = num+channelInfoModel.getActiveUser();
        }
        return num;
    }

    /**
     * 所有渠道新增
     * @param allAppStoreData
     * @return
     */
    private Integer allIncreaseMember(List<ChannelInfoModel> allAppStoreData) {
        Integer num=0;
        for(ChannelInfoModel channelInfoModel:allAppStoreData){
            num = num+channelInfoModel.getNewUser();
        }
        return num;
    }




    /**
     * 渠道活跃人数
     * @param channelMap
     * @param s
     * @return
     */
    private Integer activeMemberNum(Map<String, List<ChannelInfoModel>> channelMap, String s) {

        Integer num=0;
        List<ChannelInfoModel> channelInfoModels = channelMap.get(s);
        if(channelInfoModels==null){
            return num;
        }
        for(ChannelInfoModel channelInfoModel:channelInfoModels){
            num = num+channelInfoModel.getActiveUser();
        }
        return num;

    }

    /**
     * 渠道新增人数
     * @param channelMap
     * @param s
     * @return
     */
    private Integer increaseMemberNum(Map<String, List<ChannelInfoModel>> channelMap, String s) {
        Integer num=0;
        List<ChannelInfoModel> channelInfoModels = channelMap.get(s);
        if(channelInfoModels==null){
            return num;
        }
        for(ChannelInfoModel channelInfoModel:channelInfoModels){
            num = num+channelInfoModel.getNewUser();
        }
        return num;
    }


    /**
     * 所有渠道的数据相加
     *
     * @param cencesCoreData
     * @param all
     */
    private void sumData(CencesCoreData cencesCoreData, CencesCoreData all) {
        //新增用户(友盟)
        all.setIncreaseMember(all.getIncreaseMember() + cencesCoreData.getIncreaseMember());
        //注册人数
        all.setRegisterMember(all.getRegisterMember() + cencesCoreData.getRegisterMember());
        //活跃用户(友盟)
        all.setActiveMember(all.getActiveMember() + cencesCoreData.getActiveMember());
        //sdk营收
        all.setSdkProfit(all.getSdkProfit().add(cencesCoreData.getSdkProfit()));
        //截图营收
        all.setCommonProfit(all.getCommonProfit().add(cencesCoreData.getCommonProfit()));
        //提现支出
        all.setCashOutput(all.getCashOutput().add(cencesCoreData.getCashOutput()));
        //有效用户数
        all.setEffectMember(all.getEffectMember() + cencesCoreData.getEffectMember());
        //完成任务数
        all.setFinishTaskNun(all.getFinishTaskNun() + cencesCoreData.getFinishTaskNun());
    }

    /**
     * 获取每日必赚新用户完成任务量
     *
     * @param s
     * @param downLoadMap
     * @return
     */
    private Integer getTaskFinish(String s, Map<String, List<DownloadMemberFinishRecordCount>> downLoadMap) {
        List<DownloadMemberFinishRecordCount> downloadMemberFinishRecordCounts = downLoadMap.get(s + ":1");
        int num = 0;
        if (downloadMemberFinishRecordCounts == null) {
            return num;
        }
        for (DownloadMemberFinishRecordCount downloadMemberFinishRecordCount : downloadMemberFinishRecordCounts) {
            num = num + downloadMemberFinishRecordCount.getCount();
        }
        return num;
    }

    /**
     * 获取每日必赚新用户完成任务有效人数
     *
     * @param s
     * @param downLoadMap
     * @return
     */
    private Integer getMemberNum(String s, Map<String, List<DownloadMemberFinishRecordCount>> downLoadMap) {
        List<DownloadMemberFinishRecordCount> downloadMemberFinishRecordCounts = downLoadMap.get(s + ":1");
        int num = 0;
        if (downloadMemberFinishRecordCounts == null) {
            return num;
        }
        return downloadMemberFinishRecordCounts.size();

    }

    /**
     * 分渠道提现
     *
     * @param s
     * @param tradeMap
     * @param drawlMap
     * @return
     */
    private BigDecimal appStoreCash(String s, Map<String, List<StatisticsRecord>> tradeMap, Map<String, List<StatisticsRecord>> drawlMap) {
        List<StatisticsRecord> trades = tradeMap.get(s);
        List<StatisticsRecord> drawls = drawlMap.get(s);

        BigDecimal cash = BigDecimal.ZERO;
        if (trades != null) {
            for (StatisticsRecord statisticsRecord : trades) {
                cash = cash.add(statisticsRecord.getMyMoney());
            }
        }
        if (drawls != null) {
            for (StatisticsRecord statisticsRecord : drawls) {
                cash = cash.add(statisticsRecord.getMyMoney());
            }
        }

        return cash;

    }


    /**
     * 获取截图收益
     *
     * @param s
     * @param commonMap
     * @return
     */
    private BigDecimal appStoreCommonProfit(String s, Map<String, List<StatisticsRecord>> commonMap) {
        List<StatisticsRecord> statisticsRecords = commonMap.get(s);
        BigDecimal profit = BigDecimal.ZERO;
        if (statisticsRecords == null) {
            return profit;
        }
        for (StatisticsRecord statisticsRecord : statisticsRecords) {
            profit = profit.add(statisticsRecord.getMyMoney());
        }
        return profit;
    }

    /**
     * 获取渠道下的sdk
     *
     * @param appStore
     * @param collect
     * @return
     */
    private BigDecimal appStoreSdkProfit(String appStore, Map<String, List<CencesCoreDataModel>> collect) {

        //闲玩的SDK收入
        BigDecimal xianWanMySdkMoney = this.getSdkData(collect, TaskCategory.XianWan.name(), appStore);
        //91淘金的sdk收入
        BigDecimal taoJinMySdkMoney = this.getSdkData(collect, TaskCategory.TAOJIN.name(), appStore);
        //傲天任务的sdk收入
        BigDecimal aoTianMySdkMoney = this.getSdkData(collect, TaskCategory.AoTian.name(), appStore);
        //pc蛋蛋享玩的sdk收入
        BigDecimal danDanMySdkMoney = this.getSdkData(collect, TaskCategory.PCDANDAN.name(), appStore);
        //乐享多游的sdk收入
        BigDecimal leXiangMySdkMoney = this.getSdkData(collect, TaskCategory.LEXIANG.name(), appStore);
        //聚享玩的sdk收入
        BigDecimal juXiangWanMySdkMoney = this.getSdkData(collect, TaskCategory.JUXIANGWAN.name(), appStore);
        //鱼玩盒子的sdk收入
        BigDecimal yWHZMySdkMoney = this.getSdkData(collect, TaskCategory.YW_HZ.name(), appStore);
        //    今天我们的SDK收入
        BigDecimal todayMySdkMoney = xianWanMySdkMoney.add(taoJinMySdkMoney)
                .add(aoTianMySdkMoney)
                .add(danDanMySdkMoney)
                .add(leXiangMySdkMoney)
                .add(juXiangWanMySdkMoney)
                .add(yWHZMySdkMoney);
        return todayMySdkMoney;

    }

    /**
     * 获取sdk不同渠道的收益
     *
     * @param collect
     * @param name
     * @param appStore
     * @return
     */
    private BigDecimal getSdkData(Map<String, List<CencesCoreDataModel>> collect, String name, String appStore) {
        List<CencesCoreDataModel> cencesCoreDataModels = collect.get(name + ":" + appStore);
        BigDecimal profit = BigDecimal.ZERO;
        if (cencesCoreDataModels == null) {
            return profit;
        }
        for (CencesCoreDataModel cencesCoreDataModel : cencesCoreDataModels) {
            profit = profit.add(cencesCoreDataModel.getMyAmount());
        }
        return profit;
    }

    /**
     * 统计渠道注册人数
     *
     * @param registerMap
     * @param s
     * @return
     */
    private Integer countRegisterNum(Map<String, List<CencesCoreDataModel>> registerMap, String s) {
        int num = 0;
        List<CencesCoreDataModel> cencesCoreDataModels = registerMap.get(s);
        if (cencesCoreDataModels == null) {
            return num;
        }
        for (CencesCoreDataModel cencesCoreDataModel : cencesCoreDataModels) {
            num = num + cencesCoreDataModel.getCount();
        }
        return num;
    }


    public long countByExample(CencesCoreDataExample example) {
        return  cencesCoreDataMapper.countByExample(example);
    }

    public List<CencesCoreData> selectByExample(CencesCoreDataExample example) {
        return cencesCoreDataMapper.selectByExample(example);
    }

    public CencesCoreData selectById(Integer id) {
        return cencesCoreDataMapper.selectByPrimaryKey(id);
    }

    public void deleteByTime(Integer time,Integer appId) {
        cencesCoreDataMapper.deleteByTime(time,appId);
    }
}
